#!/usr/bin/env bash
###################
path_to_files='../.images/status/'
linkname_list='./status-linkname-list.txt'
if test ! -f "${linkname_list}" ; then
	echo "error: Missing file: ${linkname_list}"
	exit -1
fi
#
make_links() {
	function_name="make_links()"
	number_of_arguments=5
	if test ${#} -lt ${number_of_arguments} ; then
		echo "error: ${function_name}" 
		echo "       Function call with wrong number of arguments!"
		echo "       Function expects at least ${number_of_arguments} arguments!"
		echo "       Given arguments: ${@}"
		exit -1
	fi
	source_path=$(realpath --relative-to=$(realpath -e ${2}) -e ${1})
	destination_path=$(realpath -e ${2})
	shift ; shift
	file_extension=${1} ; shift
	source_filename=${1} ; shift
	destination_linkname_list=("$@")
	if test -z ${destination_path} ; then
		echo "error: ${function_name}"
		echo "       Missing link destination!"
	else
		pushd ${destination_path}
		source_file=${source_path}/${source_filename}${file_extension}
		if test ! -f "${source_file}" ; then
			echo "error: ${function_name}"
			echo "       Missing file: ${source_file}"
		else
			echo "DEBUG: ln -svf ${source_file} ${destination_path}/${source_filename}.${file_extension##*.}" >&2
			ln -svf "${source_file}" "${destination_path}/${source_filename}.${file_extension##*.}"
			for i in ${destination_linkname_list[@]} ; do
				destination_link=${destination_path}/${i}.${file_extension##*.}
				echo "DEBUG: ln -svf ${source_file} ${destination_link}" >&2
				ln -svf "${source_file}" "${destination_link}"
			done
		fi
		popd
	fi
}
#
path_to_links='./scalable/'
extension='.24x24.svg'
# DO NOT SEPARATE grep AND while LINES!
grep -v '^#.*$\|^[[:space:]]*$' ${linkname_list} |\
while IFS='' read -r line || test -n "${line}" ; do
	echo "DEBUG: make_links ${path_to_files} ${path_to_links} ${extension} ${line}" >&2
	make_links ${path_to_files} ${path_to_links} ${extension} ${line}
done
#
exit 0
